package mfuny.ggongal.admin.event;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import mfuny.ggongal.admin.Server;
import mfuny.ggongal.admin.debug.Debug;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ibatis.sqlmap.client.SqlMapClient;

public class EventService {
    SqlMapClient sqlMapper;
    ModelAndView mav;
    
    public EventService() throws Exception {
        sqlMapper = Server.getSqlMapper();
        mav = new ModelAndView();
    }
    
    //이벤트 등록.
    public ModelAndView regEvent(EventDao ev) throws Exception {
    	MultipartFile bannerFile = ev.getBannerFile();
    	String ex = bannerFile.getOriginalFilename().split("\\.")[1];
    	ev.setEv_image(System.currentTimeMillis() + "_event_" + new Random().nextInt(100) + "." + ex);
    	ev.setEv_image_capacity(bannerFile.getSize());
    	
    	int result = -1;
    	
    	try{
    		bannerFile.transferTo(new File(Server.filePath + ev.getEv_image()));
    		result = sqlMapper.update("event_insert", ev);
    		if( result <= 0 ) {
    			throw new Exception("sql 업데이트 실패.");
    		}
    		
    	}catch(Exception e) {
    		Debug.toDebugFile(e, "regEvent 에러");
    	}
    	
    	String msg = "";
    	if( result > 0 ) {
    		msg = "성공적으로 등록되었습니다.";
    	} else {
    		msg = "등록에 실패하였습니다. 다시 시도하여 주십시오.";
    	}
    	
    	mav.clear();
    	mav.setViewName("/redirect.ga");
    	mav.addObject("msg", msg);
    	mav.addObject("redirectURI", "eventList.ga");
    	
    	return mav;
    }
    
    //이벤트 리스트 페이지.
    public ModelAndView eventList() throws Exception {
    	mav.clear();
    	mav.setViewName("/event/eventList.ga");
    	return mav;
    }
    
    //이벤트 리스트 상세.
    @SuppressWarnings("unchecked")
	public ModelAndView getEventList(int num, int pageSize) throws Exception {
    	HashMap<String, Object> paramMap = new HashMap<String, Object>();
    	int pageNum = num;
    	int totalCount = (Integer) sqlMapper.queryForObject("event_totalCount", null);
    	num = pageNum == 0 ? 1 : pageNum * pageSize - pageSize;
    	
    	paramMap.put("num", num);
    	paramMap.put("pageSize", pageSize);
    	List<HashMap<String, Object>> resultList = sqlMapper.queryForList("event_selectEventList", paramMap);
    	
    	mav.clear();
    	mav.setViewName("/event/getEventList");
    	mav.addObject("resultList", resultList);
    	mav.addObject("totalCount", totalCount);
    	mav.addObject("pageNum", pageNum);
    	
    	return mav;
    }
    
    //이벤트 삭제하기.
    public ModelAndView deleteEvent(int ev_no) throws Exception {
    	int result = sqlMapper.delete("event_deleteByNo", ev_no);
    	mav.clear();
    	mav.setViewName("/blank");
    	mav.addObject("value", result);
    	
    	return mav;
    }
    
    //이벤트 수정폼.
    @SuppressWarnings("unchecked")
	public ModelAndView modifyEventForm(int ev_no) throws Exception {
    	HashMap<String, Object> resultClass = (HashMap<String, Object>)sqlMapper.queryForObject("event_selectByNoForModify", ev_no);
    	mav.clear();
    	mav.setViewName("/event/modifyEventForm.ga");
    	mav.addObject("resultClass", resultClass);
    	
    	return mav;
    }
    
    //이벤트 수정 처리.
    public ModelAndView modifyEvent(EventDao ev) throws Exception {
    	MultipartFile bannerFile = ev.getBannerFile();
    	
    	if( bannerFile.isEmpty() ) {
    		ev.setEv_image(null);
    		ev.setEv_image_capacity(0);
    	} else {
    		String ex = bannerFile.getOriginalFilename().split("\\.")[1];
        	ev.setEv_image(System.currentTimeMillis() + "_event_" + new Random().nextInt(100) + "." + ex);
        	ev.setEv_image_capacity(bannerFile.getSize());
        	try{
        		String beforeImg = (String) sqlMapper.queryForObject("event_onlyImg", ev.getEv_no());
        		new File(Server.filePath + beforeImg).delete();
        	}catch(Exception e3){}
        	
        	try {
        		bannerFile.transferTo(new File(Server.filePath + ev.getEv_image()));
        	} catch ( Exception e ) {
        		Debug.toDebugFile(e, "파일 저장 실패");
        	}
    	}
    	
    	int result = -1;
    	
    	try {
    		result = sqlMapper.update("event_update", ev);
    		if( result <= 0 ) {
    			throw new Exception("sql 업데이트 실패");
    		}
    		
    	} catch ( Exception e ) {
    		Debug.toDebugFile(e, "modifyEvent 에러");
    		if( !bannerFile.isEmpty() ) {
    			try{
    				new File(Server.filePath + ev.getEv_image()).delete();
    			}catch(Exception e2) {}
    		}
    	}
    	
    	String msg = "";
    	if( result > 0 ) {
    		msg = "성공적으로 수정되었습니다.";
    	} else {
    		msg = "수정에 실패하였습니다. 다시 시도하여 주십시오.";
    	}
    	
    	mav.clear();
    	mav.setViewName("/redirect.ga");
    	mav.addObject("msg", msg);
    	mav.addObject("redirectURI", "eventList.ga");
    	
    	return mav;
    }
}
